package tree;

import java.util.ArrayList;
import java.util.Collections;

public class HuffManTree<T> {
    private HuffManTreeNode<T> root;
    private ArrayList<HuffManTreeNode<T>> array;

    public HuffManTree() {
        array = new ArrayList<>();
    }

    public void add(Integer id, T element){
        HuffManTreeNode<T> node = new HuffManTreeNode<T>(id,element);
        array.add(node);
    }
    public void construct(){
        while(array.size()>1){
            Collections.sort(array);
            HuffManTreeNode leftNode = array.get(0);
            HuffManTreeNode rightNode = array.get(1);
            HuffManTreeNode<T> node = new HuffManTreeNode<T>(leftNode.getValue()+rightNode.getValue(),null);
            node.setLeft(leftNode);
            node.setRight(rightNode);
            array.remove(1);
            array.remove(0);
            array.add(node);
        }
        root = array.get(0);
    }

    public void preOrderPrint(){
        if(root==null){
            return;
        }
        root.preOrderPrint();
    }
}
